package com.webserver.core;

import com.webserver.Controller.ArticleController;
import com.webserver.Controller.UserController;
import com.webserver.http.HttpContext;
import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;
import com.webserver.vo.Article;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * 该类用于完成请求的处理工作
 */
public class DispatcherServlet {

    private static DispatcherServlet obj;
    private DispatcherServlet(){
    }
    public static DispatcherServlet getInstance(){
        if(obj==null){
            obj = new DispatcherServlet();
        }
        return obj;
    }


    public void service(HttpServletRequest request, HttpServletResponse response){

        String path = request.getRequestURI();
        if ("/myweb/reg".equals(path)){//如果是注册请求就执行
//            处理用户注册：
            UserController controller = new UserController();
            controller.reg(request,response);
        }else if ("/myweb/login".equals(path))  {
            //  处理用户登录：
            UserController controller = new UserController();
            controller.login(request,response);

        }else if ("/myweb/showAllUser".equals(path))  {
            //  处理用户列表：
            UserController controller = new UserController();
            controller.showAllUser(request,response);

        }else if ("/myweb/writeArticle".equals(path)){//
            //  处理发表文章：
            ArticleController controller = new ArticleController();
            controller.writeArticle(request,response);

        }else if("/myweb/showAllArticle".equals(path)){
            ArticleController controller = new ArticleController();
            controller.showAllArticle(request,response);
        }
        else {//否则执行：

            //将./webapps/myweb/index.html响应给浏览器
            File file = new File("./webapps" + path);

            if (file.isFile()) {//如果定位是./webapps的文件
                response.setEntity(file);

            } else {//否则执行：
                //不是文件(要么不存在,要么是目录，那么就是404情况)
                file = new File("./webapps/root/404.html");
                response.setStatusCode(404);
                response.setStatusReason("NotFound");
                response.setEntity(file);
            }
        }
//        告诉浏览器
        response.addHeader("Server","WebServer");

    }
}
